package com.sky.controller.user;

import com.alibaba.fastjson2.JSON;
import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Tag(name = "C端菜品浏览接口")
@Validated
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据分类id查询菜品
     * @return
     */
    @GetMapping("/list")
    @Operation(summary = "根据分类id查询菜品")
    public Result<List<DishVO>> list(@RequestParam @NotNull(message = "分类id不能为空") Long categoryId){
        String key = "sky-take-out:dishCategory:" + categoryId;
        // 先从Redis获取数据
        String dishJson = stringRedisTemplate.opsForValue().get(key);
        // 如果Redis中有数据，则反序列化为对象列表
        if (StringUtils.isNoneBlank(dishJson)){
            List<DishVO> dishVOList = JSON.parseArray(dishJson, DishVO.class);
            return Result.success(dishVOList);
        }
        // Redis中没有，则查询数据库,将查询到的数据放到redis中
        List<DishVO> dishVOList = dishService.getDishWithFlavorsByCategoryId(categoryId);
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(dishVOList),3600L, TimeUnit.MINUTES);
       if (CollectionUtils.isNotEmpty(dishVOList)){
           return Result.success(dishVOList);
       }else {
           return Result.error(MessageConstant.CATEGORY_UNDER_NODISHES);
       }
    }
}
